import entities
import menu
import service
import uicls
import collections

class ContextMenuClient(service.Service):
    __guid__ = 'svc.contextMenuClient'
    __componentTypes__ = ['contextMenu']

    def __init__(self):
        service.Service.__init__(self)
        self.components = {}



    def Run(self, *args):
        service.Service.Run(self, args)
        self.mouseInputService = sm.GetService('mouseInput')
        self.actionObjectClient = sm.GetService('actionObjectClientSvc')



    def CreateComponent(self, name, state):
        component = entities.ContextMenuComponent()
        return component



    def RegisterComponent(self, entity, component):
        if (len(self.components) == 0):
            self.mouseInputService.RegisterCallback(const.INPUT_TYPE_RIGHTCLICK, self.OnRightClick)
        if (session.role & service.ROLE_QA):
            component.menuEntries['Entity Monitor'] = self.ShowEntityMonitor
        self.components[entity.entityID] = component



    def UnRegisterComponent(self, entity, component):
        del self.components[entity.entityID]
        if (len(self.components) == 0):
            self.mouseInputService.UnRegisterCallback(const.INPUT_TYPE_RIGHTCLICK, self.OnRightClick)



    def ReportState(self, component):
        report = collections.OrderedDict()
        for (name, callback,) in component.menuEntries.iteritems():
            report[name] = str(callback).replace('<', '[').replace('>', ']')

        return report



    def AddMenuEntry(self, entityID, label, callback):
        self.components[entityID].AddMenuEntry(label, callback)



    def OnRightClick(self, entityID):
        try:
            component = self.components[entityID]
            entries = []
            for (key, value,) in component.menuEntries.iteritems():
                entries.append((key,
                 value,
                 (entityID)))

            actionList = self.actionObjectClient.GetActionList(session.charid, entityID)
            entries.append(None)
            for actionID in actionList:
                if actionList[actionID][1]:
                    args = (session.charid,
                     entityID,
                     actionID)
                else:
                    args = menu.DISABLED_ENTRY
                entries.append((actionList[actionID][0],
                 self.actionObjectClient.TriggerActionOnObject,
                 args))

            mv = menu.CreateMenuView(menu.CreateMenuFromList(entries), None, None)
            (mv.left, mv.top,) = (uicore.triapp.uilib.x, uicore.triapp.uilib.y)
            uicls.Frame(parent=mv, color=(1.0, 1.0, 1.0, 0.2))
            uicore.layer.menu.children.insert(0, mv)
        except KeyError:
            pass



    def ShowEntityMonitor(self, entityID):
        if (session.role & service.ROLE_QA):
            sm.GetService('window').GetWindow(('EntityMonitor_%d' % entityID), create=1, maximize=1, decoClass=uicls.EntityMonitor, entID=entityID)




